package com.atguigu.gulimall.cart.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @create: 2024/9/7
 * @author: gyhe10
 * @description:
 **/

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ProductFeignService productFeignService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(str)) {
            // 购物车中没有该商品，添加新商品到购物车
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                // 远程调用 product 服务接口，获取商品详情
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    Object obj = r.get("skuInfo");
                    if (obj != null) {
                        SkuInfoVo skuInfoVo = JSONUtil.toBean(JSONUtil.toJsonStr(obj), SkuInfoVo.class);
                        cartItem.setSkuId(skuId);
                        cartItem.setCheck(true);
                        cartItem.setTitle(skuInfoVo.getSkuTitle());
                        cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                        cartItem.setPrice(skuInfoVo.getPrice());
                        cartItem.setCount(num);
                    }
                }
            }, threadPoolExecutor);
            // 远程调用 product 服务接口，查询当前 SKU 的销售属性组合
            // 多次远程调用，可以考虑使用异步编排进行优化
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuSaleAttrValuesBySkuId(skuId);
                if (r.getCode() == 0) {
                    Object obj = r.get("data");
                    if (obj != null) {
                        cartItem.setSkuAttrs(JSONUtil.toList(JSONUtil.toJsonStr(obj), String.class));
                    }
                }
            }, threadPoolExecutor);
            // 等待所有异步任务全部完成
            CompletableFuture.allOf(getSkuInfo, getSkuSaleAttrValues).get();
            // 添加新购物项到购物车
            cartOps.put(skuId.toString(), JSONUtil.toJsonStr(cartItem));
            return cartItem;
        } else {
            // 购物车中有该商品，更新数量
            CartItem cartItem = JSONUtil.toBean(str, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSONUtil.toJsonStr(cartItem));
            return cartItem;
        }
    }

    /**
     * 获取购物车增删改查哈希操作对象
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 拦截器中已经将用户登录信息添加到 ThreadLocal
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        // 获取购物车 key
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            // 登录，购物车 key 为 gulimall:cart:userId
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 未登录，购物车 key 为 gulimall:cart:userKey
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }

        // 获取购物车数据
        // 获取一个绑定到哈希类型的键 cartKey 的操作对象，后续针对购物车的增删改查哈希操作不需要再关心购物车的 key
        return stringRedisTemplate.boundHashOps(cartKey);
    }

    @Override
    public CartItem getCartItemBySkuId(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        if (!StringUtils.isEmpty(str)) {
            return JSONUtil.toBean(str, CartItem.class);
        }
        return null;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 用户已登录
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            // 离线购物车中是否有购物项，如果有，则合并购物项到在线购物车中，并删除离线购物车
            String tempCartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                // 合并购物车
                for (CartItem cartItem : tempCartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                // 删除离线购物车
                clearCart(tempCartKey);
            }
            // 获取在线购物车中的购物项列表，已经包含离线购物车中的购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            // 用户未登录
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            // 获取离线购物车中的购物项列表
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 获取购物车中的购物项列表
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        if (hashOps.size() != null && hashOps.size() > 0) {
            // 购物车中存在商品
            List<Object> values = hashOps.values();
            return values.stream().map(obj -> {
                String str = (String) obj;
                return JSONUtil.toBean(str, CartItem.class);
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCheck(check == 1);
        String jsonStr = JSONUtil.toJsonStr(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonStr);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCount(num);
        String jsonStr = JSONUtil.toJsonStr(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonStr);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCheckedItems() {
        // 获取当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            if (CollectionUtil.isNotEmpty(cartItems)) {
                // 过滤出所有选中的购物项
                List<CartItem> collect = cartItems.stream().filter(CartItem::getCheck).collect(Collectors.toList());
                // 获取选中的购物项的 skuId 列表
                List<Long> skuIdList = collect.stream().map(CartItem::getSkuId).collect(Collectors.toList());
                // 远程调用商品服务，批量获取商品最新价格
                Map<Long, BigDecimal> map = productFeignService.getSkuPricesBySkuIdList(skuIdList);
                // 更新购物项的商品价格
                collect.forEach(item -> item.setPrice(map.get(item.getSkuId())));
                return collect;
            }
            return null;
        }
    }
}
